package io.github.wjehovah.yyn.fragment;


import android.annotation.TargetApi;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.MediaController;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import io.github.wjehovah.yyn.App;
import io.github.wjehovah.yyn.R;
import io.github.wjehovah.yyn.adapter.TypedListAdapter;
import io.github.wjehovah.yyn.bean.CommBean;
import io.github.wjehovah.yyn.bean.CommBean.BeanDetail;
import io.github.wjehovah.yyn.data.Budejie;
import io.github.wjehovah.yyn.utils.DimensionUtil;
import io.github.wjehovah.yyn.utils.Engine;
import io.github.wjehovah.yyn.utils.JsonUtil;
import io.github.wjehovah.yyn.utils.SharedPrefUtils;
import io.github.wjehovah.yyn.utils.TimeUtil;
import io.github.wjehovah.yyn.utils.ToastUtil;
import io.github.wjehovah.yyn.view.XListView;

/**
 * 点击顶部  indicator 对应的page
 */
public class BaseBudejieFragment extends Fragment implements XListView.IXListViewListener, AbsListView.OnScrollListener {
    @ViewInject(R.id.lv_all)
    public XListView mListView;
    private Gson gson;
    private int typeId;//用以区分 精华或者最新页面
    private int position;//标志 pager的position
    private TypedListAdapter adapter;
    private List<BeanDetail> data;
    // private String cacheId = "list1";//默认 精华-全部页面位置
    private String currentUrl;//当前页面请求的 url
    private int lastUptime;//保存更新时间戳
    private String UPDATE_SAVE_KEY;
    private String[] positionInfo;//保存ListView 位置信息

    private HttpUtils httpUtils;

    private CommBean lastBean;
    private CommBean oldBean;

    private static final String ARG_PARAM1 = "param1";
    public static final String ARG_PARAM2 = "param2";

    public static BaseBudejieFragment newInstance(String param1, String param2) {
        BaseBudejieFragment fragment = new BaseBudejieFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public BaseBudejieFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gson = new Gson();
        httpUtils = new HttpUtils(5000);
        if (getArguments() != null) {
            String value1 = getArguments().getString(ARG_PARAM1);
            String value2 = getArguments().getString(ARG_PARAM2);
            typeId = value1.equals("essence") ? 0 : 1;
            position = Integer.parseInt(value2);
            //保存最后更新时间的key
            UPDATE_SAVE_KEY = typeId + "_" + position;
        }
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //mListView.setOnScrollListener(this);
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        String positionInfo = SharedPrefUtils.getString(Budejie.POSITION, null);
        if (typeId == 0 && position == 0 && positionInfo != null) {
            typeId = Integer.valueOf(positionInfo.split("_")[0]);
            position = Integer.valueOf(positionInfo.split("_")[1]);
        }
        View view = null;

        data = new ArrayList<>();
        switch (typeId) { //typeId---底部RadioGroup的标识
            case 0://精华
                switch (position) {
                    case 0: //全部
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.ESSENCE_ALL;
                        //请求并处理 json，设置 adapter
                        questAndProcessJson(currentUrl, false);
                        return view;
                    case 1: //视频
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.ESSENCE_VIDEO_URL;
                        questAndProcessJson(currentUrl, false);
                        return view;
                    case 2: //图片
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.ESSENCE_IMG_URL;
                        questAndProcessJson(currentUrl, false);
                        return view;
                    case 3://段子
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.ESSENCE_JOKE_URL;
                        questAndProcessJson(currentUrl, false);
                        return view;

                    case 4://排行
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.ESSENCE_RANK_URL;
                        questAndProcessJson(currentUrl, false);
                        return view;
                }
            case 1://对应最新 tab
                switch (position) {
                    case 0: //全部
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.LAST_ALL;
                        questAndProcessJson(currentUrl, false);
                        return view;

                    case 1://视频
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.LAST_VIDEO;
                        questAndProcessJson(currentUrl, false);
                        return view;
                    case 2://图片
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.LAST_IMG;
                        questAndProcessJson(currentUrl, false);
                        return view;
                    case 3://段子
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.LAST_JOKE;
                        questAndProcessJson(currentUrl, false);
                        return view;

                    case 4://声音
                        view = inflater.inflate(R.layout.fragment_top_common_page, null, false);
                        ViewUtils.inject(this, view);
                        addExtraEvent();
                        currentUrl = Budejie.LAST_VOICE_URL;
                        questAndProcessJson(currentUrl, false);
                        return view;
                }
            default:
                return null;
        }
    }

    private void addExtraEvent() {
        mListView.setPullLoadEnable(true);
        mListView.setPullRefreshEnable(true);
        mListView.setXListViewListener(this);
        mListView.setOnScrollListener(this);
    }


    @Override
    public void onDetach() {
        super.onDetach();
        oldBean = null;
    }

    /**
     * @param url       请求的url
     * @param scrollTop 是否定位到ListView 首个位置
     */
    //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void questAndProcessJson(final String url, final Boolean scrollTop) {

        lastUptime = SharedPrefUtils.getInt(UPDATE_SAVE_KEY, 0);//读取 sp 保存的缓存的时间

        String updateTime = TimeUtil.getPassedMin(lastUptime);
        mListView.setRefreshTime(updateTime + "分钟前");
        String cacheId = cacheIdGenerate(url);
        String currentPositionInfo = SharedPrefUtils.getString(cacheId, "");
        if (!"".equals(currentPositionInfo)) {
            positionInfo = currentPositionInfo.split("_");
        }

        String cacheJson = JsonUtil.getJsonDiskCache(cacheId);
        if (!cacheJson.equals("")) {
            lastBean = parseJson(cacheJson);
            oldBean = lastBean;
            data.addAll(lastBean.list);
            if (adapter == null) {
                adapter = new TypedListAdapter(getActivity(), data);
                mListView.setAdapter(adapter);
            } else {
                adapter.notifyDataSetChanged();
            }
            mListView.setSelection(0);
       /*     if (positionInfo != null && !scrollTop) {
                mListView.setSelectionFromTop(Integer.valueOf(positionInfo[0]), Integer.valueOf(positionInfo[1]));
            } else if (positionInfo != null && scrollTop) {
                mListView.setSelection(Integer.valueOf(positionInfo[0]));
            }*/
        }

        //检查是否有网络
        if (Engine.Http.getAliveNetWork()) {//请求

            final String[] finalPositionInfo = positionInfo;
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String json = responseInfo.result;
                    //缓存 json
                    Log.e(Budejie.TAG + "刷新", url);
                    if (!TextUtils.isEmpty(json)) {
                        //缓存json
                        String cacheId = cacheIdGenerate(url);
                        JsonUtil.setJsonDiskCache(json, cacheId);

                        CommBean bean = parseJson(json);
                        lastUptime = (int) (System.currentTimeMillis() / 1000);
                        SharedPrefUtils.save(UPDATE_SAVE_KEY, lastUptime);
                        if (lastBean == null) {//即第一次 请求
                            lastBean = bean;
                            oldBean = bean;
                            data.addAll(bean.list);
                            adapter = new TypedListAdapter(getActivity(), data);
                            mListView.setAdapter(adapter);
                        } else {
                            //后面的请求
                            onLoadFinish();
                            if (!lastBean.info.maxtime.equals(bean.info.maxtime)) {//服务器返回新数据
                                ToastUtil.showMsg("已经加载最新" + bean.list.size() + "条数据，共" + lastBean.info.count + "条", DimensionUtil.dp2px(90));
                                lastBean = bean;
                                data.addAll(bean.list);
                                adapter.notifyDataSetChanged();
                                mListView.setSelection(0);
                                //setSelectionFromTop(mPosition, lvChildTop)
                               /* if (finalPositionInfo != null && !scrollTop) {
                                    mListView.setSelectionFromTop(Integer.valueOf(finalPositionInfo[0]), Integer.valueOf(finalPositionInfo[1]));
                                } else if (finalPositionInfo != null && scrollTop) {
                                    mListView.setSelection(Integer.valueOf(finalPositionInfo[0]));
                                }*/

                            } else {
                                //服务器没有最新数据
                                lastBean = bean;
                                //oldBean = lastBean;
                                adapter.notifyDataSetChanged();
                                mListView.setSelection(0);
                             /*   if (finalPositionInfo != null && !scrollTop) {
                                    mListView.setSelectionFromTop(Integer.valueOf(finalPositionInfo[0]), Integer.valueOf(finalPositionInfo[1]));
                                } else if (finalPositionInfo != null && scrollTop) {
                                    mListView.setSelection(Integer.valueOf(finalPositionInfo[0]));
                                }*/
                                ToastUtil.showMsg(App.getContext().getResources().getString(R.string.not_new_data_click), DimensionUtil.dp2px(90));
                            }
                        }
                        Log.e(Budejie.TAG + "id", cacheId);
                    }
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                    onLoadFinish();
                    ToastUtil.showMsg("连接网络失败，请检查后重试");
                }
            });
        } else {//没网提示并读取缓存
            ToastUtil.showMsg("连接网络失败，请检查后重试");

        }

    }

    private CommBean parseJson(String json) {
        return gson.fromJson(json, CommBean.class);

    }

    private void loadMore() {
        String moreUrl = loadMoreUrlCreate(typeId, position);
        Log.e(Budejie.TAG + "加载更多", moreUrl);
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, moreUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String json = responseInfo.result;
                if (!TextUtils.isEmpty(json)) {
                    //请求成功更新下一组数据
                    oldBean = parseJson(json);
                    data.addAll(oldBean.list);
                    adapter.notifyDataSetChanged();
                    onLoadFinish();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                onLoadFinish();
                ToastUtil.showMsg("连接网络失败，请检查后重试");
            }
        });

    }

    /**
     * @param typeId   以区分 最新或者精华
     * @param position 表示 viewpager 页面位置
     * @return 根据两个参数生成加载更多的 url
     */
    private String loadMoreUrlCreate(int typeId, int position) {
        String lastDozenId = oldBean.info.maxtime;

        switch (typeId) {
            case 0:
                switch (position) {
                    case 0:
                        return Budejie.ESSENCE_ALL + lastDozenId;
                    case 1:
                        return Budejie.ESSENCE_VIDEO_URL + lastDozenId;
                    case 2:
                        return Budejie.ESSENCE_IMG_URL + lastDozenId;
                    case 3:
                        return Budejie.ESSENCE_JOKE_URL + lastDozenId;
                    case 4:
                        return Budejie.ESSENCE_RANK_URL + lastDozenId;
                }

            case 1:
                switch (position) {
                    case 0:
                        return Budejie.LAST_ALL + lastDozenId;
                    case 1:
                        return Budejie.LAST_VIDEO + lastDozenId;
                    case 2:
                        return Budejie.LAST_IMG + lastDozenId;
                    case 3:
                        return Budejie.LAST_JOKE + lastDozenId;
                    case 4:
                        return Budejie.LAST_VOICE_URL + lastDozenId;
                }
        }

        return "";
    }

    /**
     * @param url 请求的 url  包含全部、 视频、图片、段子、排行和 声音
     * @return 缓存文件 id
     */
    private String cacheIdGenerate(String url) {
        Uri uri = Uri.parse(url);
        String a = uri.getQueryParameter("a");
        String type = uri.getQueryParameter("type");
        String order = uri.getQueryParameter("order");
        if (TextUtils.isEmpty(order)) {
            order = "";
        }
        return a + "_" + type + "_" + order;
    }


    @Override
    public void onRefresh() {
        if (Engine.Http.getAliveNetWork()) {//请求
            questAndProcessJson(currentUrl, true);
        } else {
            onLoadFinish();
        }
    }

    /**
     * 第三方xListViewhttps://github.com/Maxwin-z/XListView-Android
     * pull down refresh" and "pull up load" feature
     */
    @Override
    public void onLoadMore() {
        if (Engine.Http.getAliveNetWork()) {//请求
            loadMore();//上拉加载更多数据
        } else {
            onLoadFinish();
        }
    }

    private void onLoadFinish() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        String updateTime = TimeUtil.getPassedMin(lastUptime);
        mListView.setRefreshTime(updateTime + "分钟前");
    }

    public void buttonPressed() {
        //mListView.
        //  questAndProcessJson(currentUrl,false);
        // onRefresh();
        questAndProcessJson(currentUrl, true);
        Log.e("fragement", "ok" + currentUrl);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 不滚动时保存当前滚动到的位置
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            int firstVisiblePosition = mListView.getFirstVisiblePosition();
            View v = mListView.getChildAt(0);
            int i = (v == null) ? 0 : v.getTop();
            Log.e(Budejie.TAG + "listView", i + "---" + firstVisiblePosition);
            String keyOfPosition = cacheIdGenerate(currentUrl);
            String currentPositionInfo = firstVisiblePosition + "_" + i;
            //缓存ListView当前位置
            SharedPrefUtils.save(keyOfPosition, currentPositionInfo);
        }

        MediaController mediaController = adapter.getmMediaCtrl();
        TypedListAdapter.ViewHolder holder = adapter.getHolder1();
        if (mediaController==null||holder==null){
            return;
        }

            holder.video.seekTo(0);
            holder.video.stopPlayback();
            adapter.notifyDataSetChanged();
//                    holder.video.setVisibility(View.GONE);
//                    BeanDetail beanDetail = adapter.getBeanDetail();
//                    holder.playcount.setText("播放次数：" + beanDetail.playcount);
//                    holder.play.setImageResource(R.drawable.play);//
//                    holder.videotime.setText(beanDetail.videotime + "秒");
//                    BitmapUtils bitmapUtils=new BitmapUtils(getActivity());
//                    bitmapUtils.display(holder.image_small,beanDetail.image_small);

//                    Glide.with(getActivity()).load(beanDetail.image_small).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(holder.image_small);
//                                mediaController.hide();
//                               holder.video.pause();

        Log.e("LCY", "onScrollStateChanged++holder=" + holder.toString());
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }
}


